<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- card body -->
      <!-- 添加角色按钮区域 ,Layout 布局row行 col列-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" stripe border>
        <!-- 可展开列 -->
        <el-table-column type="expand">
          <template slot-scope="SCOPE">
            <!-- 通过for循环，渲染一级权限 -->
            <el-row
              :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vcenter']"
              v-for="(item1, i1) in SCOPE.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(SCOPE.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环，嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdTop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(SCOPE.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(SCOPE.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 平铺列-->
        <el-table-column type="index" width="100%"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <!-- 因为要用到作用域插槽引入按钮，prop会被覆盖，所以不需要添加prop -->
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditRoleDia(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="30%"
      @close="setRightDialogClose"
    >
      <!-- 树形控件 -->
      <!-- data数据源 props指定数据字段 
    default-expand-all默认展开 
    show-checkbox前面是否有选择框
    node-key绑定勾选的当前值是什么来作为唯一标识属性，我们设置成id，即以后key就是id
    default-expanded-keys默认展开节点的 key 组成的数组-->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色组件 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close="addRoleDialogClosed"
    >
      <!-- 内容里替换为表格组件 status-icon属性为输入框添加校验结果对错的图标-->
      <el-form
        :model="addRoleForm"
        status-icon
        ref="addRoleRef"
        :rules="addRoleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色组件 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      @close="editRoleDialogClosed"
    >
      <!-- 内容里替换为表格组件 status-icon属性为输入框添加校验结果对错的图标-->
      <el-form
        :model="editRoleForm"
        status-icon
        ref="editRoleRef"
        :rules="editRoleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolelist: [],
      //分配权限对话框的显示隐藏
      setRightDialogVisible: false,
      //所有的权限数据
      rightslist: [],
      //树形控件的属性绑定对象
      //label指定节点标签名字,children指定父子通过哪个关节名字实现嵌套
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的id数组
      defkeys: [],
      //手动分配权限的那个角色id，从展示分配权限的对话框showSetRightDialog获取
      roleId: [],
      //点击添加角色按钮显示隐藏
      addRoleDialogVisible: false,
      //点击添加角色按钮后展示的表单数据，用model绑定
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      //添加表单的验证规则对象,用rules绑定
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请选择活动资源', trigger: 'change' }
        ]
      },
      //编辑表单的验证规则对象
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请选择活动资源', trigger: 'change' }
        ]
      },
      //点击修改角色按钮显示隐藏
      editRoleDialogVisible: false,
      //查询返回的角色对象放这里
      editRoleForm: {}
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('请求角色列表失败')
      } else {
        this.rolelist = res.data
        console.log('角色列表:', this.rolelist)
      }
    },
    //根据Id删除对应的权限
    async removeRightById(role, rightId) {
      //弹框
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('你取消删除了')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      /* 不建议调用初始化角色列表，因为会发生页面渲染导致展开栏关闭。只需
      把服务器返回的权限赋值给children */
      role.children = res.data
    },
    //展示分配权限的对话框
    async showSetRightDialog(role) {
      //保存角色id，点击确定后的发送请求时会用到
      this.roleId = role.id
      //获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      //加载全部数据，把获取到的权限数据保存到data中
      this.rightslist = res.data
      console.log(this.rightslist)
      //加载勾选的权限，调用递归方法获取第三级节点的id
      this.getLeafKeys(role, this.defkeys)
      //数据加载完后打开对话框
      this.setRightDialogVisible = true
    },
    //定义递归方法，获取角色下所有三级权限的id，并保存到展开数组中defKeys
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children属性，代表这是三级节点了
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => this.getLeafKeys(item, arr))
      }
    },
    //对话框关闭后清空展示权限数组的数据
    setRightDialogClose() {
      this.defkeys = []
    },
    //点击按钮为角色分配权限
    async allotRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    //监听添加角色的关闭事件
    addRoleDialogClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    //点击添加按钮，添加新角色
    addRoles() {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          this.$message.error('新角色添加失败')
        }
        this.$message.success('新角色添加成功')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    //点击编辑按钮，编辑当前角色
    async showEditRoleDia(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      }
      this.editRoleForm = res.data
      console.log(this.editRoleForm)
      this.editRoleDialogVisible = true
    },
    //点击取消重置
    editRoleDialogClosed() {
      this.$refs.editRoleRef.resetFields()
    },
    //点击确定验证
    editRoles() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }
        this.$message.success('更新用户信息成功！')
        this.editRoleDialogVisible = false
        //重新获取角色列表
        this.getRolesList()
      })
    },
    //点击删除按钮
    async removeRoleById(id) {
      const isconfirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      /*记得return终止向下执行删除操作 */
      if (isconfirm !== 'confirm') {
       return this.$message.error('取消删除角色')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.getRolesList()
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
